package com.heima.media.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.media.dto.ChannelDto;
import com.heima.media.entity.WmChannel;
import com.heima.media.mapper.WmChannelMapper;
import com.heima.media.service.WmChannelService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;

@Service
public class WmChannelServiceImpl extends ServiceImpl<WmChannelMapper, WmChannel> implements WmChannelService {

    /**
     * 根据频道名称分页查询列表
     * @param dto
     * @return
     */
    @Override
    public ResponseResult listByName(ChannelDto dto) {
        //构建分页条件
        IPage<WmChannel> pageParam = new Page<>(dto.getPage(), dto.getSize());
        //构建查询条件
        LambdaQueryWrapper<WmChannel> qw = new LambdaQueryWrapper<>();
        //判断传入的名称不为空，添加频道名称条件
        if (!StringUtils.isEmpty(dto.getName())) {
            qw.like(WmChannel::getName,dto.getName());
        }
        IPage<WmChannel> iPage = this.page(pageParam,qw);
        //构建分页响应
        PageResponseResult result = new PageResponseResult(dto.getPage(),dto.getSize(),iPage.getTotal(),iPage.getRecords());
        return result;
    }

    /**
     * 新增频道
     * @param channel
     * @return
     */
    @Override
    public ResponseResult saveChannel(WmChannel channel) {
        //参数校检
        if (channel == null || StringUtils.isEmpty(channel.getName())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //判断频道名称如果存在，不允许新增,根据频道名称查询数据数量
        LambdaQueryWrapper<WmChannel> qw = new LambdaQueryWrapper<>();
        qw.eq(WmChannel::getName,channel.getName());
        int count = this.count(qw);
        if (count > 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST);
        }
        //判断频道名称，新增保存
        channel.setCreatedTime(new Date());
        this.save(channel);
        return ResponseResult.okResult();
    }
}
